const studentWork = require('../models/studentWork')
const users = require('../models/users')
const course = require('../models/course')
const formidable = require('formidable')
const node_xlsx = require('node-xlsx')
const fs = require('fs')
const send = require('koa-send')
/**
 *

    获取全部学生作业信息（老师用）


 */
var getStuWork = async(ctx,next)=>{
    var stuArr1 = await studentWork.find({workName:ctx.request.body.workName,course:ctx.request.body.course}).sort({"studentID":1})
    if(stuArr1[0].endTime<Date.now()){
        for(var i = 0;i<stuArr1.length;i++){
            if(stuArr1[i].accessory==""){
                await studentWork.findByIdAndUpdate(stuArr1[i]._id,{$set:{workStatus:0}})
            }
        }
    }
    var stuArr = new Array();
    var oCourse = await course.findOne({course:ctx.request.body.course})
    oCourse.student.sort();
    for(var i=0;i<oCourse.student.length;i++){
        var stuWork = await studentWork.findOne({studentID:oCourse.student[i],workName:ctx.request.body.workName,course:ctx.request.body.course});
        stuArr.push(stuWork)
    }

    ctx.response.body = {stauts:'success',msg:'获取成功',stuArr};
}
/**
 *
 *
 * 提交作业
 * userID,workName,course,上传的文件
 *
 */
var submitWork = async(ctx,next)=>{
    var submit = async function(newPath,fields){
        var document = await studentWork.findOne({studentID:fields.userID,workName:fields.workName,course:fields.course});
        await studentWork.findByIdAndUpdate(document._id,{$set:{accessory:newPath,submitTime:Date.now()}})
        if(document.endTime<Date.now()){
            await studentWork.findByIdAndUpdate(document._id,{$set:{workStatus:-1}})
        }else{
            await studentWork.findByIdAndUpdate(document._id,{$set:{workStatus:2}})
        }
        return 'success'
    }
    ///////////////////////////
    var fileParse = async function(){
        var form = new formidable.IncomingForm();
            form.encoding = 'utf-8';
            form.uploadDir = './upload/work/';
            form.keepExtensions = true;
            form.maxFieldsSize = 2*1024*1024;
        return new Promise((resolve,reject)=>{
            form.parse(ctx.req,async function(err,fields,files){
                if(err){
                    console.log(form);
                    console.log(err);
                    return;
                }
                var is = await fs.existsSync('./upload/work/'+fields.course+'/'+fields.workName)
                if(!is){
                    await fs.mkdir('./upload/work/'+fields.course+'/'+fields.workName,function(err){
                        if(err){
                            console.log(err);
                        }
                    })
                }
                var fileName = files.fileName.name;
                var isfile = await fs.existsSync('./upload/work/'+fields.course+'/'+fields.workName+'/'+fileName)
                if(isfile){
                    await fs.unlink('./upload/work/'+fields.course+'/'+fields.workName+'/'+fileName,function(err){
                        console.log(err);
                    })
                }
                var newPath = form.uploadDir+fields.course+'/'+fields.workName+'/'+fileName;
                console.log(newPath);
                await fs.renameSync(files.fileName.path,newPath);
                console.log("重命名成功")
                ////////////////////
                var res1=await submit(newPath,fields);
                if(res1=='success')
                resolve("success");
            })
        })
    }
    //////////////
    var res = await fileParse()
    if(res=="success"){
        ctx.response.body = {stauts:'success',msg:'提交成功'};
    }
}
/**
 *
 *
 * 获取学生的作业信息（学生用）
 *
 */
var getStuWork_stu = async(ctx,next)=>{
    var stu = await studentWork.findOne({studentID:ctx.request.body.userID,
        workName:ctx.request.body.workName,course:ctx.request.body.course})
    ctx.response.body = {stauts:'success',msg:'获取成功',stu};
}
/**
 *
 *
 * 获取某学生的全部作业信息
 *
 */
var getStuWork_all = async(ctx,next)=>{
    var stu = await studentWork.find({studentID:ctx.request.body.userID})
    ctx.response.body = {stauts:'success',msg:'获取成功',stu};
}

/**
 *
 * 获取历史作业
 * userID
 *
 */
var getStuWork_his = async(ctx,next)=>{
    var stu = await users.findOne({userID:ctx.request.body.userID})
    var courseArr = stu.course;
    var arr = new Array()
    var x = 0
    var bool = false
    for(var i=0;i<courseArr.length;i++){
        var w = await studentWork.find({studentID:ctx.request.body.userID,course:courseArr[i]})
        for(var j=0;j<w.length;j++){
            if(!w[j].accessory==""){
                if(w[j].endTime<Date.now()){
                    arr[x] = new Array();
                    arr[x].push(w[j]);
                    bool = true;
                }
            }
        }
        if(bool){
            x++;
            bool=false;
        }
    }
    console.log(arr);
    return  ctx.response.body = {stauts:'success',msg:'获取成功',arr};
}
 /**
  * 
    下载学生作业
    workName，course，userID

  */
  var download_stu = async(ctx,next)=>{
    var document = await studentWork.findOne({studentID:ctx.params.userID,workName:ctx.params.workName,course:ctx.params.course})
    if(document.accessory==""){
        return ctx.response.body = {stauts:'error',msg:'该学生未提交作业'};
    }
    var fileName = document.accessory.substring(document.accessory.lastIndexOf("/")+1,document.accessory.length);
    var path = document.accessory;
    console.log(path);
    ctx.attachment(fileName);
    await send(ctx, path);
 }
 /**
  * 
  * 评分
  * workName，course，userID,score,evaluate(可以为空)
  * 
  */
  var setScore = async(ctx,next)=>{
    var document = await studentWork.findOne({studentID:ctx.request.body.userID,workName:ctx.request.body.workName,course:ctx.request.body.course})
    console.log(document);
    if(!document){
        return ctx.response.body = {stauts:'error',msg:'作业不存在'};
    }
    if(document.accessory==""){
        return ctx.response.body = {stauts:'error',msg:'该学生未提交作业'};
    }
    await studentWork.findByIdAndUpdate(document._id,{$set:{score:ctx.request.body.score,evaluate:ctx.request.body.evaluate}})
    return ctx.response.body = {stauts:'success',msg:'成功'};
 }
module.exports = {
    'POST /studentWork/getStuWork': getStuWork,
    'POST /studentWork/submitWork': submitWork,
    'POST /studentWork/getStuWork_stu': getStuWork_stu,
    'POST /studentWork/getStuWork_all': getStuWork_all,
    'POST /studentWork/getStuWork_his': getStuWork_his,
    'POST /studentWork/setScore': setScore,
    'GET /studentWork/download_stu/:workName/:course/:userID': download_stu,
}
